package utils

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func (c *GoGo_Utils_Class) FileReadAll(fileName string) []byte {
	if fileName == "" {
		return nil
	}

	fileHandle, err := os.Open(fileName)
	if err == nil {
		defer fileHandle.Close()

		var fileBytes []byte
		if fileBytes, err = io.ReadAll(fileHandle); err == nil {
			return fileBytes
		}
	}

	return nil
}

func (c *GoGo_Utils_Class) FileMkdir(fileName string) bool {
	if fileName == "" {
		return false
	}

	_, err := os.Stat(fileName)
	if err != nil {
		if err = os.MkdirAll(fileName, 0777); err == nil {
			return true
		}
	}

	return false
}

func (c *GoGo_Utils_Class) FileDelAll(fileName string) bool {
	if fileName == "" {
		return false
	}

	err := os.RemoveAll(fileName)
	if err == nil {
		return true
	}

	return false
}

func (c *GoGo_Utils_Class) FileDel(fileName string) bool {
	if fileName == "" {
		return false
	}

	err := os.Remove(fileName)
	if err == nil {
		return true
	}

	return false
}

func (c *GoGo_Utils_Class) FileAppend(fileName string, fileBytes []byte) bool {
	if fileName == "" {
		return false
	}

	if fileBytes == nil {
		return false
	}

	fileHandle, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if err == nil {
		defer fileHandle.Close()
		if _, err = fileHandle.Write(fileBytes); err == nil {
			return true
		}
	}

	return false
}

// 判断文件是否存在
func (c *GoGo_Utils_Class) FileExist(fileName string) bool {
	if fileName == "" {
		return false
	}

	// 读取文件信息，判断文件是否存在
	_, err := os.Stat(fileName)
	if err == nil || os.IsExist(err) {
		return true
	}

	return false
}

// 计算文件大小
func (c *GoGo_Utils_Class) FileSize(fileName string) int64 {
	if fileName == "" {
		return -1
	}

	fi, err := os.Stat(fileName)
	if err != nil {
		return -1
	}
	return fi.Size()
}

// 判断文件名含有value的文件是否存在
func (c *GoGo_Utils_Class) FileExistHasPrefix(path, value string) bool {
	files, err := os.ReadDir(path)
	if err != nil {
		return false
	}

	for _, file := range files {
		if file.IsDir() {
			return c.FileExistHasPrefix(path+"/"+file.Name(), value)
		} else {
			if strings.HasPrefix(file.Name(), value) {
				return true
			}
		}
	}

	return false
}

func (c *GoGo_Utils_Class) FileCopy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}
